package com;

import inputHelp.Utf7ImeHelper;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;

import android.os.RemoteException;


import com.android.uiautomator.core.UiObject;
import com.android.uiautomator.core.UiObjectNotFoundException;
import com.android.uiautomator.core.UiScrollable;
import com.android.uiautomator.core.UiSelector;
import com.android.uiautomator.testrunner.UiAutomatorTestCase;
import com.db.TxtHelper;

public class CopyJi extends UiAutomatorTestCase {
	
	
	//复读主方法， 主要是获取元素，再获取语句，进行转换后发送
	//copyType： 1图灵；2直接复读
	TxtHelper txtHelper = new TxtHelper();
	DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	/**
	 * @param chat   qq的哪一个会话
	 * @param timeLoop  复读一次后等待时间
	 * @param serverIP  图灵服务器地址 一般是本地
	 * @param copyType  1图灵；2直接复读
	 * @param isImg  0不复读图片；1复读图片
	 * @throws RemoteException
	 * @throws UiObjectNotFoundException
	 * @throws IOException
	 */
	

	
	public void fudu(String chat1,String chat2,  String serverIP,int copyType,int isImg ,int isCopy2,int isLight) throws RemoteException,
			UiObjectNotFoundException, IOException {
		String text = "";
		int count = 0;
		int tcount = 0;
        System.out.println(sdf.format(new Date())); 
        
		while(true){
			sleep(3000);
			UiObject uio;
			if(isLight==0)
				 uio = getDescUiO();
			else 
				uio = getDescUiO3();
			UiObject uiot = null;
			if (null==uio||!uio.exists()) {
				System.out.println("!!!!: uio not exits");
				continue;
			}
			//System.out.println(uio.getSelector());
			/*if(uio.getChild(new UiSelector().className(
					"android.widget.TextView")).exists()){
				System.out.println(uio.getChild(new UiSelector().className(
							"android.widget.TextView").index(4)).isFocusable());
			}*/
			if(uio.getChild(new UiSelector().className(
					"android.widget.TextView")).exists() && uio.getChild(new UiSelector().className(
							"android.widget.TextView").index(4)).exists() && uio.getChild(new UiSelector().className(
							"android.widget.TextView").index(4)).isFocusable()){
				
				//System.out.println();
				uiot = uio.getChild(new UiSelector().className(
						"android.widget.TextView").index(4));
				tcount++;
			}else if(uio.getChild(new UiSelector().className(
					"android.widget.TextView")).exists() && uio.getChild(new UiSelector().className(
							"android.widget.TextView").index(5)).exists() && uio.getChild(new UiSelector().className(
							"android.widget.TextView").index(5)).isFocusable()){
				
				//System.out.println();
				uiot = uio.getChild(new UiSelector().className(
						"android.widget.TextView").index(5));
				tcount++;
			}else if(uio.getChild(new UiSelector().className(
					"android.widget.TextView")).exists() && uio.getChild(new UiSelector().className(
							"android.widget.TextView").index(3)).exists() && uio.getChild(new UiSelector().className(
							"android.widget.TextView").index(3)).isFocusable()){
				
				//System.out.println();
				uiot = uio.getChild(new UiSelector().className(
						"android.widget.TextView").index(3));
				tcount++;
			}
			
			else if(uio.getChild(new UiSelector().className(
					"android.widget.LinearLayout")).exists()){
					UiObject uioabs = uio.getChild(new UiSelector().className("android.widget.LinearLayout"));
					for (int i = 0; i < uioabs.getChildCount(); i++) {
						UiObject uio5 = uioabs.getChild(new UiSelector().index(i));
						if (uio5.exists() && uio5.isFocusable()) {
							uiot = uio5;
							break;
							}
							/*else { 
								System.out.println("!!!no linearlayout/textview");
								continue;
							}*/
					}
					tcount++;
					System.out.println("!!! at linearlayout");
			}else { 
				tcount++;
				System.out.println("!!!no textview");
				continue;
				}
			if(null==uiot||!uiot.exists()){
				continue;
			}
			text = uiot.getText();
			if(text.contains("。；")){
				continue;
			}
			if(text.contains("我") || text.contains("你")){
				txtHelper.insertTmp(text.replace("@", ""));
			}
			
			if(text.length()<(9+Math.round(Math.random()*4))) {
				System.out.println("short:"+text);
				continue;
			}
			System.out.println("original："+text);
			
			
			//如果已经复读过，就不复读了
			//如果没复读就加入库里面
			
			if(txtHelper.isExist(text)){
				System.out.println(sdf.format(new Date())+ "!!text exist!!");
				continue;
			}else{
				txtHelper.insertMsg(text);
				text = replace(text);
				txtHelper.insertMsg(text);
				if(copyType==1){
					text = summary(text,serverIP);//使用中文语言服务器的summary方法进行转换
					if(text==null ||text=="null")
						continue;
					txtHelper.insertMsg(text);
				}else if(copyType==0) {  //默认复读别人的话
					 
				}
				sendText(text);
				if(isCopy2 == 1){
					System.out.println("sendText2 ing");
					sendText2(text, chat1, chat2);
				}
			}
		
			//text = strRandom(text);
			System.out.println("$$$copy Times:  " + count);
			System.out.println("$$$try Times:  " + tcount);
			count++;
			sleep(10*1000+Math.round(Math.random()*5*1000));
		}
		
	}
	
	public static String replace(String str){
		str = str.replace("@", "");
		char[] arr = str.toCharArray();
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i <= arr.length-1; i++) {
			if('我'==arr[i]){
				arr[i]='你';
			}else if ('你'==arr[i]) {
				arr[i]='我';
			}else if ('他'==arr[i]) {
				arr[i]='你';
			}
			sb.append(arr[i]);
		}
		return sb.toString();
	}
	
	// 字符串倒转
	public static String upDown(String str) {
		char[] arr = str.toCharArray();
		StringBuffer sb = new StringBuffer();
		for (int i = arr.length; i > 0; i--) {
			sb.append(arr[i - 1]);
		}
		return sb.toString();
	}

	// 字符串无序
	public static String strRandom(String str) {
		char[] sequence = str.toCharArray();
		StringBuffer sb = new StringBuffer();
		Random random = new Random();
		for (int i = 0; i < sequence.length; i++) {
			int p = random.nextInt(sequence.length);
			char tmp = sequence[i];
			sequence[i] = sequence[p];
			sequence[p] = tmp;
		}
		random = null;
		for (int t = 0; t < sequence.length; t++) {
			sb.append(sequence[t]);
		}
		return sb.toString();
	}

	// 处理desc，针对“说”、“我说”、“发送了图片”等字样
	public static String descHandle(String desc) {
		if (desc.contains(":说")) {
			desc = desc.substring(desc.indexOf(":说") + 2, desc.length());
		} else if (desc.contains("我说")) {
			desc = desc.substring(desc.indexOf("我说") + 2, desc.length());
		} else if (desc.contains("发送了图片")) {
			desc = "";
		}
		return desc;
	}

	
	public static UiObject getDescUiO3()
			throws UiObjectNotFoundException {
		//System.out.print("geting Frame1");
		// 一层层获取
		UiObject uio1 = new UiObject(new UiSelector().className(
				"android.widget.FrameLayout").index(0));
		if(uio1.exists()){
			//System.out.print("geting relative0");
			UiObject uio2 = uio1.getChild(new UiSelector().className(
					"android.widget.RelativeLayout").index(0));
			if(uio2.exists()){
				//System.out.print("geting abslist2");
				UiObject uio3 = uio2.getChild(new UiSelector().className(
						"android.view.View"));
				if(uio3.exists()){
					UiObject uio4 ;
					//System.out.print("geting relativeN");
					uio4 = getDesc(uio3);
					return uio4;
				}else return null;
			}else return null;
		}else return null;
	}
	
	public static UiObject getDescUiO()
			throws UiObjectNotFoundException {
		//System.out.print("geting Frame1");
		// 一层层获取
		UiObject uio1 = new UiObject(new UiSelector().className(
				"android.widget.FrameLayout").index(1));
		if(uio1.exists()){
			//System.out.print("geting relative0");
			UiObject uio2 = uio1.getChild(new UiSelector().className(
					"android.widget.RelativeLayout").index(0));
			if(uio2.exists()){
				//System.out.print("geting abslist2");
				UiObject uio3 = uio2.getChild(new UiSelector().className(
						"android.widget.AbsListView"));
				if(uio3.exists()){
					UiObject uio4 ;
					//System.out.print("geting relativeN");
					uio4 = getDesc(uio3);
					return uio4;
				}else return null;
			}else return null;
		}else return null;
	}
	
	
	
	public static UiObject getTitleUiO()
			throws UiObjectNotFoundException {
		// 一层层获取
		UiObject uio1 = new UiObject(new UiSelector().className(
				"android.widget.RelativeLayout").index(0));
		if(uio1.exists()){
			UiObject uio2 = uio1.getChild(new UiSelector().className(
					"android.widget.RelativeLayout").index(0));
			if(uio2.exists()){
				UiObject uio3 = uio2.getChild(new UiSelector().className(
						"android.widget.RelativeLayout").index(0));
				if(uio3.exists()){
					UiObject uio4 =uio3.getChild(new UiSelector().className(
							"android.widget.LinearLayout")) ;
					if(uio4.exists()){
						UiObject uio5 =uio4.getChild(new UiSelector().className(
								"android.widget.TextView")) ;
						return uio5;
					} else return null;
				}else return null;
			}else return null;
		}else return null;
	}
	
	
	public static UiObject getDesc(UiObject uio) throws UiObjectNotFoundException{
		UiObject uioDesc = null;
		for(int i =6;i>=0;i--){
			if(uio.getChild(new UiSelector().className(
					"android.widget.RelativeLayout").index(i)).exists()){
				
				uioDesc = uio.getChild(new UiSelector().className(
						"android.widget.RelativeLayout").index(i));
				break;
			}//else System.out.println(uio.getChildCount()+"uio.getChildCount()");
		}
		return uioDesc;
	}

	public static void sendText(String desct) throws UiObjectNotFoundException {
		UiObject textform = new UiObject(
				new UiSelector().className("android.widget.EditText"));
		textform.click();
		// System.out.println("###"+desct);
		textform.setText(Utf7ImeHelper.e(desct));
		new UiObject(new UiSelector().text("发送")).click();
		// sleep(50000);
	}

	public static void sendText2(String desct,String chat1,String chat2) throws UiObjectNotFoundException {
		new UiObject(new UiSelector().text(chat1)).clickAndWaitForNewWindow();
		//new UiObject(new UiSelector().resourceId("com.tencent.mobileqq:id/ivTitleBtnLeft")).clickAndWaitForNewWindow();
		new UiObject(new UiSelector().text(chat2)).clickAndWaitForNewWindow();
		//new UiObject(new UiSelector().className("android.widget.LinearLayout").index(2)).clickAndWaitForNewWindow();
		
		UiObject textform = new UiObject(
				new UiSelector().className("android.widget.EditText"));
		textform.click();
		// System.out.println("###"+desct);
		textform.setText(Utf7ImeHelper.e(desct));
		new UiObject(new UiSelector().text("发送")).click();
		new UiObject(new UiSelector().text(chat2)).clickAndWaitForNewWindow();
		//new UiObject(new UiSelector().resourceId("com.tencent.mobileqq:id/ivTitleBtnLeft")).clickAndWaitForNewWindow();
		new UiObject(new UiSelector().text(chat1)).clickAndWaitForNewWindow();
		//new UiObject(new UiSelector().className("android.widget.LinearLayout").index(1)).clickAndWaitForNewWindow();
		// sleep(50000);
	}
	
	
	public static void copyImg(String chat, UiObject uio)
			throws UiObjectNotFoundException {
		UiObject img = uio.getChild(
				new UiSelector().className("android.widget.RelativeLayout"))
				.getChild(
						new UiSelector().className("android.widget.ImageView"));
		if (!img.exists()) {
			img = uio.getChild(
					new UiSelector().className("android.widget.LinearLayout"))
					.getChild(
							new UiSelector()
									.className("android.widget.ImageView"));
		}
		if (img.exists()) {

			img.clickAndWaitForNewWindow(5000);
			// sleep(5000);
			new UiObject(
					new UiSelector().className("android.widget.ImageButton"))
					.clickAndWaitForNewWindow(1000);
			// sleep(1000);
			new UiObject(new UiSelector().text("发送给好友"))
					.clickAndWaitForNewWindow();
			UiScrollable tItems = new UiScrollable(
					new UiSelector().scrollable(true));
			UiObject mItem = tItems.getChildByText(new UiSelector().text(chat),
					chat, true);
			mItem.clickAndWaitForNewWindow();
			new UiObject(new UiSelector().text("发送"))
					.clickAndWaitForNewWindow();
		}
	}
	
public static String summary(String text,String serverIP) throws UnknownHostException, IOException{
		
		//向服务器端发送请求，服务器IP地址和服务器监听的端口号
		Socket client = new Socket(serverIP, 4242);
		
                  //通过printWriter 来向服务器发送消息
		PrintWriter printWriter = new PrintWriter(client.getOutputStream());
		//System.out.println("连接已建立...");
                  
                  //发送消息
		printWriter.println(text);
		
		printWriter.flush();
		
		//InputStreamReader是低层和高层串流之间的桥梁
		//client.getInputStream()从Socket取得输入串流
		InputStreamReader streamReader = new InputStreamReader(client.getInputStream());
		
		//链接数据串流，建立BufferedReader来读取，将BufferReader链接到InputStreamReder
		BufferedReader reader = new BufferedReader(streamReader);
		String advice =reader.readLine();
		
		
		//System.out.println("接收到服务器的消息 ："+advice);
		reader.close();
		
		if(advice.startsWith("["))
			advice = advice.substring(1);
		if(advice.endsWith("]"))
			advice = advice.substring(0, advice.length()-1);
		
		return advice;
	}
	
}
